package com.kongshidian.ui;

import java.lang.ref.WeakReference;
import java.util.List;
import java.util.Map;

import net.tsz.afinal.FinalActivity;
import net.tsz.afinal.annotation.view.ViewInject;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.kongshidian.App;
import com.kongshidian.R;
import com.kongshidian.bean.OrderList;
import com.kongshidian.bean.OrderList.OrderItemDTOs;
import com.kongshidian.bean.OrderList.OrderStatus;
import com.kongshidian.bean.OrderList.PaymentStatus;
import com.kongshidian.http.WebClient;
import com.kongshidian.http.WebException;
import com.kongshidian.util.ContextUtil;
import com.kongshidian.util.DateTimeUtil;
import com.kongshidian.util.StringUtil;
import com.nostra13.universalimageloader.core.ImageLoader;

/**
 * @author fbl
 * 订单详情
 */
@SuppressLint("HandlerLeak") public class OrderDetailActivity extends BackableTitleBarActivity{


	@ViewInject(id = R.id.order_datail_state) TextView mOrderStateText;  //订单状态
	@ViewInject(id = R.id.order_datail_number) TextView mOrderNumberText; // 订单号
	@ViewInject(id = R.id.order_datail_username) TextView mOrderUserNameText; //用户名
	@ViewInject(id = R.id.order_datail_userphone) TextView mOrderUserPhoneText; //用户联系方式
	@ViewInject(id = R.id.order_datail_useraddress) TextView mOrderUserAddressText; //收货地址
	@ViewInject(id = R.id.order_datail_order_macketprice) TextView mOrderMacketPriceText; //商品销售价
	@ViewInject(id = R.id.order_datail_order_price) TextView mOrderPriceText;     //商品总价
	@ViewInject(id = R.id.order_datail_order_freight) TextView mOrderFreightText; //运费
	@ViewInject(id = R.id.order_datail_delivery_way) TextView mOrderDeliveryWayText; //快递
	@ViewInject(id = R.id.order_datail_logistics_number) TextView mOrderLogisticsNumberText; //物流编号
	@ViewInject(id = R.id.order_datail_logistics_time) TextView mOrderLogisticsTimeText; //配送时间
	@ViewInject(id = R.id.order_datail_invoice) TextView mOrderInvoiceText; //发票信息
	@ViewInject(id = R.id.order_datail_invoice_taitou) TextView mOrderInvoiceTaitouText; //发票抬头
	@ViewInject(id = R.id.order_datail_invoice_count) TextView mOrderInvoiceCountText; //发票内容
	@ViewInject(id = R.id.order_detail_invoice_relat) RelativeLayout mOrderInvoiceRelat; //发票relat
	@ViewInject(id = R.id.order_datail_totle_price) TextView mOrderTotlePriceText; //总计价格
	@ViewInject(id = R.id.order_products_lin) LinearLayout mProductsLin; //商品视图
	@ViewInject(id = R.id.order_datail_submit_but ,click="butClick") Button mSureBut; //提交订单button

	private String  sn;
	private OrderList mOrderDetail;
	private Handler mHandler = new MyHandler(this);


	//-------------------------------------------------------------

	@Override
	protected void onCreate(Bundle savedInstance) {
		super.onCreate(savedInstance);
		setContentView(R.layout.activity_order_detail);
		getTitleBar().setTitle(R.string.title_order_detail);
		FinalActivity.initInjectedView(this);

		sn = getIntent().getStringExtra("sn");

		getOrderDetailData();



	}

	private void getOrderDetailData() {
		showLoadingDialog(""); //Status Report ...

		new Thread(){
			public void run() {
				try {
					mOrderDetail = WebClient.getInstance(OrderDetailActivity.this).getOrderDetail(sn);
					mHandler.sendEmptyMessage(0);
				} catch (WebException e) {
					dismissLoadingDialog();
					e.printStackTrace();
				}catch (Exception e) {
					dismissLoadingDialog();
				}
			};
		}.start();

	}



	@SuppressWarnings("static-access")
	private void updateUIStatus(OrderStatus orderStatus,PaymentStatus paymentStatus){
		if(OrderStatus.unconfirmed.equals(orderStatus)){

			mOrderStateText.setText( "待付款");

			mSureBut.setText("去付款");
			mSureBut.setVisibility(View.VISIBLE);

		}else if(OrderStatus.confirmed.equals(orderStatus)){

			if(paymentStatus.equals( paymentStatus.partialPayment)){

				mOrderStateText.setText( "待付款");				
				mSureBut.setText("去付款");
			}else if(paymentStatus.equals( PaymentStatus.paid)){

				mOrderStateText.setText( "待发货");

				mSureBut.setText("等待收货");
			}else{
				//其他方式
			}

			mSureBut.setVisibility(View.VISIBLE);
		}else if (OrderStatus.completed.equals(orderStatus) || OrderStatus.returned.equals(orderStatus) 
				|| OrderStatus.exchanged.equals(orderStatus)) {

			mOrderStateText.setText( "已完成");

			mSureBut.setText("评价/晒单");
			mSureBut.setVisibility(View.VISIBLE);

		}else if(OrderStatus.cancelled.equals(orderStatus) ){

			mOrderStateText.setText( "已取消");

			mSureBut.setText("评价/晒单");
			mSureBut.setVisibility(View.VISIBLE);

		}else if(OrderStatus.orderReceived.equals(orderStatus) || OrderStatus.stockVerifying.equals(orderStatus) 
				||OrderStatus.purchasing.equals(orderStatus) || OrderStatus.picking.equals(orderStatus)){

			mOrderStateText.setText( "待发货");

			mSureBut.setText("确认收货");
			mSureBut.setVisibility(View.VISIBLE);

		}else if (OrderStatus.returning.equals(orderStatus)) {

			mOrderStateText.setText( "退货中");
			mSureBut.setVisibility(View.GONE);
			//无须评价
		}else if (OrderStatus.exchanging.equals(orderStatus)) {

			mOrderStateText.setText( "换货中" );
			mSureBut.setVisibility(View.GONE);
			//无须评价
		}else if (OrderStatus.toBeConfirmed.equals(orderStatus)) {

			mOrderStateText.setText( "待收货");

			mSureBut.setText("确认收货");
			mSureBut.setVisibility(View.VISIBLE);
			//无须评价
		}else if(OrderStatus.shipped.equals(orderStatus)){

			mOrderStateText.setText( "待收货");

			mSureBut.setText("确认收货");
			mSureBut.setVisibility(View.VISIBLE);
			//无须评价
		}else if(OrderStatus.MEMBER_SIGNED.equals(orderStatus)){
			//已完成
			mOrderStateText.setText("已完成");
			
			if( !mOrderDetail.isReviewStatus() && !mOrderDetail.isSunSingleStatus() ){
				mSureBut.setText("评价/晒单");	
			}else if(!mOrderDetail.isReviewStatus() && mOrderDetail.isSunSingleStatus()){
				mSureBut.setText("评价");	
			}else if(mOrderDetail.isReviewStatus() && !mOrderDetail.isSunSingleStatus()){
				mSureBut.setText("晒单");	
			}
			
			mSureBut.setVisibility(View.VISIBLE);
		}
	}

	private void initData(){
		//mOrderStateText.setText(OrderUtil.getOrderStatus(mOrderDetail.getOrderStatus()));
		mOrderNumberText.setText(mOrderDetail.getSn()+"");
		mOrderUserNameText.setText(mOrderDetail.getConsignee());
		mOrderUserPhoneText.setText(mOrderDetail.getPhone());
		mOrderUserAddressText.setText(mOrderDetail.getAreaName()+mOrderDetail.getAddress());
		mOrderPriceText.setText("￥"+mOrderDetail.getPrice());
		mOrderFreightText.setText("￥"+mOrderDetail.getFreight());
		mOrderDeliveryWayText.setText(mOrderDetail.getDeliveryCorpName());
		mOrderLogisticsNumberText.setText(mOrderDetail.getTrackingNo());
		mOrderLogisticsTimeText.setText(DateTimeUtil.getDateTime(mOrderDetail.getCreateDate()));
		mOrderTotlePriceText.setText("￥"+(mOrderDetail.getPrice()+mOrderDetail.getFreight()));

		if(mOrderDetail.getIsInvoice()){
			mOrderInvoiceText.setText("普通发票");
			mOrderInvoiceRelat.setVisibility(View.VISIBLE);
			mOrderInvoiceTaitouText.setText(mOrderDetail.getInvoiceTitle());
		}else {
			mOrderInvoiceText.setText("没开发票");
			mOrderInvoiceRelat.setVisibility(View.GONE);
		}

		updateUIStatus(mOrderDetail.getOrderStatus(),mOrderDetail.getPaymentStatus());


		List<OrderItemDTOs> mDtOs = mOrderDetail.getOrderItemDTOs();

		mProductsLin.removeAllViews();
		
		for (int i = 0; i < mDtOs.size(); i++) {

			RelativeLayout convertView =  (RelativeLayout) LayoutInflater.from(OrderDetailActivity.this).inflate(R.layout.item_order_products, null);	

			ImageView mImg = (ImageView) convertView.findViewById(R.id.order_datail_product_image);
			TextView mProName = (TextView) convertView.findViewById(R.id.order_datail_product_name);
			TextView mProNumber = (TextView) convertView.findViewById(R.id.order_datail_product_num);
			TextView mProAttribute = (TextView) convertView.findViewById(R.id.order_datail_product_attribute);

			ImageLoader.getInstance().displayImage(mDtOs.get(i).getItem().getImage(), mImg);
			mProName.setText(mDtOs.get(i).getItem().getName());
			mProNumber.setText(mDtOs.get(i).getQuantity()+"");
			//取出颜色 尺寸
			Map<String, String > maps = mDtOs.get(i).getItem().getValues();

			mProAttribute.setText(StringUtil.getProductPropertyforMap(maps));    // 商品颜色
			//根据goodsId跳转
			final String goodsId = mDtOs.get(i).getItem().getProductId()+"";
			convertView.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View view) {
					Intent intent = new Intent(OrderDetailActivity.this,ProductDetailActivity.class);
					intent.putExtra("productID", goodsId);
					startActivity(intent);
				}
			});

			mProductsLin.addView(convertView);
		}
	}
	public void butClick(View v){

		if( v == mSureBut){

			OrderStatus orderStatus = mOrderDetail.getOrderStatus();
//			PaymentStatus paymentStatus = mOrderDetail.getPaymentStatus();

			if(OrderStatus.unconfirmed.equals(orderStatus)){
				//待付款。。。
				App.showShortToast("去付款");

			}else if(OrderStatus.confirmed.equals(orderStatus)){
				//已接单，待发货。。。
				App.showShortToast("已接单，待发货");
				
			}else if (OrderStatus.completed.equals(orderStatus) || OrderStatus.returned.equals(orderStatus) 
					|| OrderStatus.exchanged.equals(orderStatus)) {
				//已完成，退换货。。。
				

			}else if(OrderStatus.cancelled.equals(orderStatus) ){
				//已取消。。。。

			}else if(OrderStatus.orderReceived.equals(orderStatus) || OrderStatus.stockVerifying.equals(orderStatus) 
					||OrderStatus.purchasing.equals(orderStatus) || OrderStatus.picking.equals(orderStatus)){
				//发货中。。。



			}else if (OrderStatus.returning.equals(orderStatus)) {
				//退货中

			}else if (OrderStatus.exchanging.equals(orderStatus)) {
				//换货中

			}else if (OrderStatus.toBeConfirmed.equals(orderStatus)) {
				//

			}else if(OrderStatus.shipped.equals(orderStatus)){
				// 已发货,待确认 

				doSignIn(mOrderDetail.getSn()+"");
				
			}else if(OrderStatus.MEMBER_SIGNED.equals(orderStatus)){
				//已完成
				
				ContextUtil.startActivity(this, EvaluationOrSunSingleActivity.class);
				
			}

		}
	}

	/**
	 *  确认收货
	 * @param mOrderSn
	 */
	private void doSignIn(final String mOrderSn) {
		showLoadingDialog("");
		
		new Thread(){
			public void run() {
				try {
					mOrderDetail = WebClient.getInstance(OrderDetailActivity.this).SignOrder(mOrderSn);
					mHandler.sendEmptyMessage(0);
					
				} catch (WebException e) {
					dismissLoadingDialog();
					e.printStackTrace();
				}catch (Exception e) {
					App.showShortToast(R.string.unknownerror);
				}
			};
		}.start();


	}



	private class MyHandler extends Handler{

		private WeakReference<Activity> mActivity;

		private MyHandler(Activity activity){
			mActivity = new WeakReference<Activity>(activity);
		}

		@Override
		public void dispatchMessage(Message msg) {
			super.dispatchMessage(msg);
			if( mActivity.get() != null ){
				switch (msg.what) {
				case 0:
					dismissLoadingDialog();
					initData();
					break;

				default:
					break;
				}
			}
		}
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		mHandler.removeCallbacksAndMessages(null);
	}



}
